<template>
  <div class='container'>
    <div class="app-container">
      <!-- 卡片区域 -->
      <el-card
        class="box-card"
        header="试题录入"
      >
        <!-- 表单 -->
        <el-form
          class="newQuestionsForm"
          ref="newQuestionsFormRef"
          :model="newQuestionsForm"
          :rules="newQuestionsFormRules"
          label-width="100px"
        >
          <!-- 学科 -->
          <el-form-item
            label="学科："
            prop="subjectID"
          >
            <el-select
              class="oneInput"
              v-model="newQuestionsForm.subjectID"
              placeholder="请选择"
              @change="onSubjectChange"
            >
              <el-option
                v-for="item in subjects"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item
            label="目录："
            prop="catalogID"
          >
            <el-select
              class="oneInput"
              v-model="newQuestionsForm.catalogID"
              placeholder="请选择"
            >
              <el-option
                v-for="item in directorys"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item
            label="企业："
            prop="enterpriseID"
          >
            <el-select
              class="oneInput"
              v-model="newQuestionsForm.enterpriseID"
              placeholder="请选择"
            >
              <el-option
                v-for="item in companys"
                :key="item.value"
                :label="item.company"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-row class="province-row">

            <el-form-item
              label="城市："
              prop="province"
            >
              <el-select
                v-model="newQuestionsForm.province"
                class="twoInput"
                placeholder="请选择"
                @change="onProvinceChange"
              >
                <el-option
                  v-for="(item,index) in provinces"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              class="province-item"
              prop="city"
            >
              <el-select
                v-model="newQuestionsForm.city"
                class="twoInput"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item,index) in citys"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>

          </el-row>
          <!-- 方向 -->
          <el-form-item
            label="方向："
            prop="direction"
          >
            <el-select
              class="oneInput"
              v-model="newQuestionsForm.direction"
              placeholder="请选择"
            >
              <el-option
                v-for="(item,index) in directions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <!-- 题型 -->
          <el-form-item
            label="题型："
            prop="questionType"
          >
            <el-radio-group v-model="newQuestionsForm.questionType">
              <el-radio
                v-for="(item,index) in questionTypeArr"
                :key="index"
                :label="item.value+''"
              >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item
            label="难度："
            prop="difficulty"
          >
            <el-radio-group v-model="newQuestionsForm.difficulty">
              <el-radio
                v-for="(item,index) in difficultyArr"
                :key="index"
                :label="item.value+''"
              >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item
            label="题干："
            prop="question"
          >
            <quill-editor
              v-model="newQuestionsForm.question"
              :options="editorOption"
            />

          </el-form-item>
          <!-- 选项 -->
          <el-form-item
            label="选项："
            v-if="newQuestionsForm.questionType !== '3'"
          >
            <!-- 选项单选框 -->
            <el-radio-group
              v-if="newQuestionsForm.questionType === '1'"
              v-model="radioSelected"
            >
              <el-col
                class="option-col"
                v-for="(n,index) in 4 "
                :key="index"
              >
                <el-radio
                  class="option-val"
                  :label="index"
                >
                  {{String.fromCharCode(asciiNum+n)+' :'}}
                </el-radio>
                <el-input
                  class="option-inp"
                  v-model="optionsArr[index].title"
                ></el-input>

                <el-upload
                  :show-file-list="false"
                  action="https://jsonplaceholder.typicode.com/posts/"
                >
                  <div class="upload-box">
                    <el-button
                      plain
                      class="upload-btn"
                    >上传图片</el-button>
                    <i class="el-icon-circle-close"></i>
                  </div>
                </el-upload>
              </el-col>
            </el-radio-group>

            <!-- 选项多选框 -->
            <el-checkbox-group
              v-model="checkboxSelected"
              v-else
            >
              <el-col
                class="option-col"
                v-for="(n,index) in optionscheckboxNum "
                :key="index"
              >
                <el-checkbox
                  class="option-val"
                  :label="index"
                >
                  {{String.fromCharCode(asciiNum+n)+' :'}}
                </el-checkbox>
                <el-input
                  class="option-inp"
                  v-model="checkoutboxOptionArr[index].title"
                ></el-input>

                <el-upload
                  :show-file-list="false"
                  action="https://jsonplaceholder.typicode.com/posts/"
                >
                  <div class="upload-box">
                    <el-button
                      plain
                      class="upload-btn"
                    >上传图片</el-button>
                    <i class="el-icon-circle-close"></i>
                  </div>
                </el-upload>
              </el-col>

            </el-checkbox-group>
            <el-button
              type="danger"
              size="small"
              :disabled="newQuestionsForm.questionType === '1'"
              @click="addCheckboxOption"
            >+添加选项与答案</el-button>

          </el-form-item>
          <!-- 解析视频 -->
          <el-form-item label="解析视频:">
            <el-input
              class="oneInput"
              v-model="newQuestionsForm.videoURL"
            ></el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item
            label="答案解析："
            prop="answer"
          >
            <quill-editor
              v-model="newQuestionsForm.answer"
              :options="editorOption"
            />

          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注:">
            <el-input
              class="oneInput"
              type="textarea"
              v-model="newQuestionsForm.remarks"
            ></el-input>
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item
            label="试题标签："
            prop="tags"
          >
            <el-select
              class="oneInput"
              v-model="newQuestionsForm.tags"
              placeholder="请选择"
              multiple
            >
              <el-option
                v-for="item in tagsList"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 提交按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              @click="addNewQuestion"
            >确认提交</el-button>

          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// 导入富文本
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
// 导入学科api
import { simple as subjectsSimple } from '@/api/hmmm/subjects'
// 导入目录列表api
import { simple as directorysSimple } from '@/api/hmmm/directorys'
// 导入企业列表api
import { list as companysList } from '@/api/hmmm/companys'
// 导入城市api
import { provinces, citys } from '@/api/hmmm/citys'
// 导入方向、难度、题型
import { direction, difficulty, questionType } from '@/api/hmmm/constants'
// 导入试题标签api
import { simple as tagsSimple } from '@/api/hmmm/tags'
// 导入提交题库api
import { add as addQuestions, detail as detailQuestions, update as updateQuestions } from '@/api/hmmm/questions'

export default {
  // 组件名称
  name: 'NewQuestions',
  // 局部注册的组件
  components: {
    quillEditor
  },
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data () {
    return {
      // 判断第几次修改学科
      changeSubjectNum: 1,
      cangeProvinceNum: 1,
      applyNum: 1,
      // 是否是修改题库
      isEditQuestions: false,
      // 修改当前题库的id
      editID: '',
      // 选项ABCD....
      asciiNum: 64,
      // 选项多选框数量
      optionscheckboxNum: 4,
      // form表单数据
      newQuestionsForm: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [], // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      // 表单验证规则
      newQuestionsFormRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        tags: [
          { required: true, message: '请选择试题标签', trigger: 'blur' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请选择题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入题目解析', trigger: 'blur' }
        ]
      },
      // 富文本toolbar 菜单
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote'], // 引用，代码块
            ['code-block', 'image', 'link'] // 上传图片、上传视频
          ]
        }

      },
      // 学科数据
      subjects: [],
      // 目录数据
      directorys: [],
      // 企业列表
      companys: [],
      // 城市数据
      provinces: [],
      // 城市地区数据
      citys: [],
      // 方向
      directions: [],
      // 试题标签
      tagsList: [],
      // 难度数据
      difficultyArr: [],
      // 题型数据
      questionTypeArr: [],
      // 单选选中项
      radioSelected: '',
      // 单选选项数组
      optionsArr: [
        { isRight: false, code: '', title: '', img: '' },
        { isRight: false, code: '', title: '', img: '' },
        { isRight: false, code: '', title: '', img: '' },
        { isRight: false, code: '', title: '', img: '' }
      ],
      // 多选选中项
      checkboxSelected: [],
      // 多选框选项数组
      checkoutboxOptionArr: [
        { isRight: false, code: '', title: '', img: '' },
        { isRight: false, code: '', title: '', img: '' },
        { isRight: false, code: '', title: '', img: '' },
        { isRight: false, code: '', title: '', img: '' }
      ]
    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {
    $route (to) {
      // console.log(to.query.id)
      if (!to.query.id) {
        this.isEditQuestions = false
        this.optionscheckboxNum = 4
        this.newQuestionsForm = {
          subjectID: '', // 学科
          catalogID: '', // 目录
          enterpriseID: '', // 企业
          province: '', // 城市
          city: '', // 地区
          direction: '', // 方向
          questionType: '1', // 题型
          difficulty: '1', // 难度
          question: '', // 题干
          options: [], // 选项
          videoURL: '', // 解析视频
          answer: '', // 答案解析
          remarks: '', // 题目备注
          tags: '' // 试题标签
        }
        this.optionsArr = [
          { isRight: false, code: '', title: '', img: '' },
          { isRight: false, code: '', title: '', img: '' },
          { isRight: false, code: '', title: '', img: '' },
          { isRight: false, code: '', title: '', img: '' }
        ]
        this.checkoutboxOptionArr = [
          { isRight: false, code: '', title: '', img: '' },
          { isRight: false, code: '', title: '', img: '' },
          { isRight: false, code: '', title: '', img: '' },
          { isRight: false, code: '', title: '', img: '' }
        ]
        this.radioSelected = ''
        this.checkboxSelected = []
        this.directorys = []
        this.citys = []
        this.tagsList = []
        this.$refs.newQuestionsFormRef.resetFields()
      }
    }
  },
  // 生命周期钩子   注：没用到的钩子请自行删除
  /**
* 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
*/
  created () {
    // 获取地址栏的参数

    // console.log(this.$router)
    // 获取学科
    this.loadSubjectsSimple()
    // 获取企业
    this.loadCompanysList()
    // 获取城市
    this.loadProvinces()
    // console.log(difficulty)
    this.directions = direction
    this.difficultyArr = difficulty
    this.questionTypeArr = questionType
    // 获取修改问题的数据

    this.editQuestionData()
  },
  /**
* el 被新创建的 vm.el 替换，并挂载到实例上去之后调用该钩子。
* 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.el 也在文档内。
*/
  mounted () {
  },
  // 组件方法
  methods: {

    // 获取到修改题库的数据
    async editQuestionData () {
      // 获取地址栏传来的id
      this.editID = this.$route.query.id
      // 如果获取到url的后缀 并且后缀里面可以查id
      if (this.editID) {
        this.isEditQuestions = true

        try {
          const { data } = await detailQuestions({ id: this.editID })

          // 把表单数据赋值
          this.newQuestionsForm = data
          // 把字符串tags分隔为数组
          this.newQuestionsForm.tags = this.newQuestionsForm.tags.split(',')
          // 获取选项框数据
          if (this.newQuestionsForm.questionType === '1') {
            // 赋值单选框的数据
            this.optionsArr = this.newQuestionsForm.options
            // 正确选项
            this.radioSelected = this.newQuestionsForm.options.findIndex(value => {
              return value.isRight === 1
            })
          } else if (this.newQuestionsForm.questionType === '2') {
            // 获取多选框的数据
            this.checkoutboxOptionArr = this.newQuestionsForm.options
            // 多选数据框的数量
            this.optionscheckboxNum = this.newQuestionsForm.options.length
            // 多选正确选项
            this.newQuestionsForm.options.forEach((item, index) => {
              if (item.isRight === 1) {
                this.checkboxSelected.push(index)
              }
            })
          }
          // 调用当前学科的目录和试题标签
          this.onSubjectChange()
          // 调用当前城市的地区
          this.onProvinceChange()
          this.$nextTick(() => {
            scrollTo(0, 0)
          })
        } catch (err) {
          console.log(err)
          this.$message.error('获取数据失败，请刷新重试')
        }
      }
    },
    // 加载学科
    async loadSubjectsSimple () {
      try {
        const { data } = await subjectsSimple()
        // console.log(data)

        this.subjects = data
      } catch (err) {
        console.log(err)
      }
    },
    // 学科改变，重新加载目录和试题标签
    async onSubjectChange () {
      if (!this.isEditQuestions || this.changeSubjectNum !== 1) {
        this.newQuestionsForm.catalogID = ''
        this.newQuestionsForm.tags = ''
      }
      this.changeSubjectNum++

      // console.log(this.newQuestionsForm.subjectID)
      if (this.newQuestionsForm.subjectID) {
        try {
          const { data: directorysData } = await directorysSimple({
            subjectID: this.newQuestionsForm.subjectID
          })
          // console.log(data)
          this.directorys = directorysData

          const { data: tagsData } = await tagsSimple({
            subjectID: this.newQuestionsForm.subjectID
          })
          // console.log(tagsData)
          this.tagsList = tagsData
        } catch (err) {
          console.log(err)
        }
      }
    },
    // 获取企业
    async loadCompanysList () {
      try {
        const { data } = await companysList()
        // console.log(data.items)
        this.companys = data.items
      } catch (err) {
        console.log(err)
      }
    },
    // 获取城市province
    async loadProvinces () {
      try {
        this.provinces = await provinces()
        // console.log(data)
      } catch (err) {
        console.log(err)
      }
    },
    // 城市改变，获取地区
    async onProvinceChange () {
      if (!this.isEditQuestions || this.cangeProvinceNum !== 1) {
        this.newQuestionsForm.city = ''
      }
      this.cangeProvinceNum++
      if (this.newQuestionsForm.province) {
        try {
          this.citys = await citys(this.newQuestionsForm.province)
          // console.log(data)
        } catch (err) {
          console.log(err)
        }
      }
    },
    // 添加多选框
    addCheckboxOption () {
      this.optionscheckboxNum++
      this.checkoutboxOptionArr.push({ isRight: false, code: '', title: '', img: '' })
    },
    // 选项数据
    setOptionsArr () {
      // questionType: '1', // 题型
      // 如果题型为单选  赋值选项code和选中项isRight
      if (this.newQuestionsForm.questionType === '1') {
        this.optionsArr.forEach((item, index) => {
          item.code = String.fromCharCode(65 + index)
          item.isRight = false
        })
        if (this.radioSelected) {
          this.optionsArr[this.radioSelected].isRight = true
        }
        this.newQuestionsForm.options = this.optionsArr
      } else if (this.newQuestionsForm.questionType === '2') {
        // 如果题型为多选  赋值选项code和选中项isRight
        this.checkoutboxOptionArr.forEach((item, index) => {
          item.code = String.fromCharCode(65 + index)
          item.isRight = false
        })
        if (this.checkboxSelected) {
          this.checkboxSelected.forEach(item => {
            this.checkoutboxOptionArr[item].isRight = true
          })
        }
        this.newQuestionsForm.options = this.checkoutboxOptionArr
      }
    },

    // 表单提交
    addNewQuestion () {
      this.$refs.newQuestionsFormRef.validate(async valid => {
        this.setOptionsArr()
        console.log(this.checkoutboxOptionArr)
        if (!valid) {
          return this.$message.error('请填写所有必填项！')
        }
        if (this.newQuestionsForm.tags) {
          this.newQuestionsForm.tags = this.newQuestionsForm.tags.join(',')
        }
        try {
          if (this.isEditQuestions) {
            await updateQuestions({ id: this.editID, ...this.newQuestionsForm })
            this.$message.success('修改成功')
          } else {
            await addQuestions(this.newQuestionsForm)
            this.$message.success('添加成功')
          }
          this.$refs.newQuestionsFormRef.resetFields()
          this.$router.push('list')
        } catch (err) {
          // console.log(err.response.status)
          this.newQuestionsForm.tags = this.newQuestionsForm.tags.split(',')
          if (err.response.status === 422 && this.isEditQuestions) {
            return this.$message.error('修改失败，请填写所有数据重试')
          }
          this.$message.error('添加失败，请稍后重试')
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.newQuestionsForm {
  padding-left: 20px;
  .oneInput {
    width: 400px;
  }
  .twoInput {
    width: 197px;
    margin-right: 6px;
    // float: left;
  }
  .option-col {
    display: flex;
    // justify-content: center;
    align-items: center;
    margin-bottom: 15px;
    .option-inp {
      width: 240px;
      margin-right: 5px;
    }
    .upload-box {
      position: relative;
      .upload-btn {
        height: 60px;
        width: 100px;
        border-style: dashed;
        color: #000;
      }
      .el-icon-circle-close {
        position: absolute;
        top: -10px;
        right: -10px;
        font-size: 20px;
        color: #aaa;
        z-index: 2;
        background-color: #fff;
      }
    }
    .option-val {
      margin-right: 10px;
    }
  }
  .province-row {
    display: flex;
    ::v-deep .province-item {
      .el-form-item__content {
        margin-left: unset !important;
      }
    }
  }
}
</style>
